#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
#define TASK_NUM 5
typedef void (*task_t)();
void download()
{
    cout << "this is a download is running" << endl;
}

void printlog()
{
    cout << "this is a printlog si running" << endl; 
}

void show()
{
    cout << "this is a show info task is running" <<endl;
}


void Worker(int cnt)
{
    cout << "I am child, pid:" << getpid() << " ppid:" << getppid() << " cnt:" << cnt << endl;
}

void InitTasks(task_t task[], int num)
{
    for(int i = 0; i < num; i++)
    {
        task[i] = NULL;
    }
}
int AddTasks(task_t tasks[], task_t t )
{
    for(int i = 0; i < TASK_NUM; i++)
    {
        if(tasks[i] == NULL)
        {
            tasks[i] = t;
            return 1;
        }
    }
    return 0;
}

void executeTask(task_t tasks[], int num)
{
    for(int i = 0; i < num; i++)
    {
        if(tasks[i])
        {
            tasks[i](); 
        }
    }
}
int main()
{

    task_t tasks[TASK_NUM];
    InitTasks(tasks, TASK_NUM);
    AddTasks(tasks,download);
    AddTasks(tasks,printlog);
    AddTasks(tasks,show);
    pid_t id = fork();
    if(id == 0)
    {
        int cnt = 10;
        while(cnt)
        {
            Worker(cnt);
            cnt--;
            sleep(1);
        }
        exit(0);
    }
    while(1)
    {
         int status = 0;
         pid_t rid = waitpid(id, &status, WNOHANG);
         if(rid > 0)
         {
             cout << "child quit success, exit code:" << ((status >> 8) & 0xFF)<< " exit signal:"<< (status&0x7F) << endl;
             break;
         }
         else if(rid == 0)
         {
             executeTask(tasks, TASK_NUM);
             cout << "child is alive, father do other thing....." << endl;
         }
         else
         {
            cout << "wait failed" << endl; 
            break;
         }
         sleep(1);
    }
    return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
